package org.bmp.zemail.login.user.services;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.bmp.zemail.login.user.models.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.stereotype.Service;

@Service
public class UserDao {
	
	private final static StringBuffer SQL_SELECT_USER = new StringBuffer("SELECT public_key, ").
			append("enabled FROM users WHERE username = ?");
	private final static StringBuffer SQL_SELECT_USER_PRIVATE_KEY = new StringBuffer("SELECT private_key ").
			append("FROM users_secure WHERE users_username = ?");
	
	/*
	 * Spring injection
	 */
	@Autowired private DataSource dataSource;
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	@Autowired private DataSource dataSourceSecure;
	public void setDataSourceSecure(DataSource dataSourceSecure) {
		this.dataSourceSecure = dataSourceSecure;
	}

	public User getUser(final String username) {		
		final DefaultLobHandler lobHandler = new DefaultLobHandler();
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<User> users = (List<User>) jdbcTemplate.query(SQL_SELECT_USER.toString(), 
				new RowMapper<User>() {

			@Override
			public User mapRow(ResultSet rs, int pos) throws SQLException {
				User user = new User();
				user.setUsername(username);
				user.setPublic_key(lobHandler.getBlobAsBytes(rs, "public_key"));
				user.setEnabled(rs.getBoolean("enabled"));
				return user;
			}
			
		}, username);
		
		
		if (users.size() != 1) {
			return null;
		}
		
		return users.get(0);
	}
	
	public byte[] getUserPrivateKey(String username) {
		final DefaultLobHandler lobHandler = new DefaultLobHandler();
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceSecure);
		
		List<byte[]> encodedPrivateKeys = jdbcTemplate.query(SQL_SELECT_USER_PRIVATE_KEY.toString(), 
				new RowMapper<byte[]>() {

			@Override
			public byte[] mapRow(ResultSet rs, int pos) throws SQLException {
				return lobHandler.getBlobAsBytes(rs, "private_key");
			}
		}, username);
		
		if (encodedPrivateKeys.size() != 1) {
			return null;
		}
		
		return encodedPrivateKeys.get(0);
	}
}
